/* eslint-disable array-callback-return */
/* eslint-disable curly */
/* eslint-disable no-negated-condition */
/* eslint-disable react/sort-comp */
import React from 'react';
import {Spin, Card, Button, Table, Row, Col, Form} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {noticeImportant} from '../Enum';
import routes from './routes';
import {TABLE, FILES_API, FORM_OPTIONS} from '../constants';
import {conventEnumValueToString} from '../utils';
import {getDetail, signforData} from './api';
import {injectIntl} from './intl';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import FileUpload from './FileUpload';
const FormItem = Form.Item;
const {Description} = DescriptionList;
const EMPTY_ARRAY = [];
class SignforPanel extends React.PureComponent {
    state = {
        loading: false,
        isFetching: false,
        hasOperat: false,
        data: {},
        details: [],
        attachments: [],
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok) {
                    if(res.data.details[0].isSigned !== true) {
                        signforData(id, {rowVersion: res.data.rowVersion})
                            .then(res => {
                                if(res.ok) {
                                    getDetail(id)
                                        .then(res => {
                                            if(res.ok) {
                                                this.setState({
                                                    isFetching: false,
                                                    data: res.data,
                                                    details: res.data.details,
                                                    attachments: res.data.attachments
                                                });
                                            } else {
                                                this.setState(({
                                                    isFetching: false
                                                }));
                                            }
                                        });
                                } else {
                                    this.setState(({
                                        isFetching: false
                                    }));
                                }
                            });
                    } else {
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.details,
                            attachments: res.data.attachments
                        });
                    }
                // eslint-disable-next-line curly
                } else {
                    this.setState(({
                        isFetching: false
                    }));
                }
            });
    };
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onRemove = data => {
        const {details = []} = this.state;
        const {attachments = []} = details.find(item => item.dealerId === this.state.currentDetailId) || {};
        const errorDetails = attachments.length - 1 <= 0 ? [...this.state.errorDetails, {
            id: this.state.currentDetailId
        }] : this.state.errorDetails;
        this.setState({
            hasOperat: true,
            errorDetails
        });
        this.onRemoveAttachments(data, this.state.currentDetailId);
    }
    onRemoveAttachments = (data, currentDetailId) => {
        const details = this.state.details || [];
        let attachments = [];
        const tmp = details.map(d => {
            if(d.dealerId === currentDetailId) {
                attachments = d.attachments || [];
                attachments.splice({
                    fileId: data.fileId,
                    fileName: data.fileName
                }, 1);
                return Object.assign({}, d, {
                    attachments: [...attachments]
                });
            }
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onReplyContentChange = value => {
        const details = this.state.details || [];
        const detail = details[0];
        detail.replyContent = value;
        details[0] = detail;
        this.setState({
            details,
            hasOperat: true
        });
    }
    onChangeUpload = data => {
        const details = this.state.details;
        const detail = details[0];
        detail.attachments.push({
            fileId: data[0].fileId,
            fileName: data[0].fileName,
        });
        details[0] = detail;
        this.setState({
            details,
            hasOperat: true
        });
    }
    removeFilePath = file => {
        const details = this.state.details;
        const index = details[0].attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = details[0].attachments || [];
        attachments.splice(index, 1);
        details[0] = details[0].attachments = {
            ...attachments
        };
        
        if(!this.state.hasOperat)
            this.setState({
                details,
                hasOperat: true,
            });
    }
    onSubmit = () => {
        const {data, details} = this.state;
        // const isValid = newOrUpdateValidator(data, details);
        // if(!isValid) {
        //     this.setState({
        //         validate: true
        //     });
        //     return;
        // }
        this.setState({loading: true});
        const detailDatas = {
            replyContent: details[0].replyContent,
            attachments: details[0].attachments ? details[0].attachments.map(o => ({
                fileId: o.fileId,
                fileName: o.fileName
            })) : undefined
        };
        this.props.onSubmit(data, detailDatas).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {data, details, loading, attachments} = this.state;
        const {formatMessage} = this.props.intl;
        let replyAttachments = [];
        if(details[0])
            replyAttachments = details[0].attachments;
        const columns = [
            {
                title: formatMessage({
                    id: 'signforPanel.column.replyContent',
                    defaultMessage: '回复内容'
                }),
                dataIndex: 'replyContent',
                render: (text, record) => (
                    <FormItem>
                        <TextInput
                            type="textarea"
                            name="replyContent"
                            value={record.replyContent}
                            onBlur={this.onReplyContentChange}/>
                    </FormItem>
                )
            }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'signforPanel.card.notice',
                                defaultMessage: '签收回复主单'
                            })
                        }</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.code',
                                defaultMessage: '编号'
                            })}>{data.code}
                            </Description>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.name',
                                defaultMessage: '主题'
                            })}>{data.name}
                            </Description>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.programName',
                                defaultMessage: '栏目'
                            })}>{data.programName}
                            </Description>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.important',
                                defaultMessage: '重要度'
                            })}>{conventEnumValueToString(noticeImportant, data.important)}
                            </Description>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.isNeedReply',
                                defaultMessage: '是否需要回复'
                            })}>{data.isNeedReply ? formatMessage({
                                    id: 'signforPanel.operation.yes',
                                    defaultMessage: '是'
                                }) : formatMessage({
                                    id: 'signforPanel.operation.no',
                                    defaultMessage: '否'
                                })}
                            </Description>
                            <Description term={formatMessage({
                                id: 'signforPanel.operation.content',
                                defaultMessage: '内容'
                            })}>{data.content}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        {attachments && attachments.length >= 0
                            ? <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.card.attachment',
                                defaultMessage: '主单附件'
                            })}>
                                {attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList size="large" title={formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}>
                            </DescriptionList>}
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'signforPanel.table.details',
                            defaultMessage: '签收回复清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={replyAttachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'newPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

SignforPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onSignfor
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, detailDatas) => dispatch(onSignfor(data, detailDatas)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SignforPanel));
